package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.service.ILikeService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikeServiceImpl implements ILikeService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveLike(LikesBehaviorDto dto) {
        // 构建 ApLikesBehavior
        ApLikesBehavior behavior = new ApLikesBehavior();

        User user = AppThreadLocalUtil.get();
        if (user != null) {
            behavior.setUserId(user.getUserId());
        } else {
            behavior.setEquipmentId(dto.getEquipmentId());
        }
        behavior.setArticleId(dto.getArticleId());
        behavior.setType(0);
        behavior.setOperation(dto.getOperation());
        behavior.setCreatedTime(new Date());

        // 保存用户的点赞记录

        // 判断当前用户对当前文章是否已经有点赞记录
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (user == null) {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        } else {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }
        ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
        // 如果没有,新增记录
        if (one == null) {
            if (dto.getOperation() == 0) {
                mongoTemplate.save(behavior);
                sendMessage(dto);
            }
        } else {
            // 如果有,判断当前的操作和数据库中的操作是否一致
            if (one.getOperation() != dto.getOperation()) {
                // 如果不一致,修改操作类型,更新记录
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                sendMessage(dto);
            }
        }


        return ResponseResult.okResult();
    }

    /**
     * 查询点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<ApLikesBehavior> getLikes(LikesBehaviorDto dto) {
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId() == null) {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        } else {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        }
        ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
        return ResponseResult.okResult(one);
    }

    /**点赞消息到kafka
     * 发送
     * @param dto
     */
    private void sendMessage(LikesBehaviorDto dto) {
        //发送点赞消息到kafka
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setType(1);
        message.setArticleId(dto.getArticleId());
        message.setAdd(1);
        if (dto.getOperation() == 1){
            message.setAdd(-1);
        }
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(LikeTopic,value);
    }

    @Value("${topic.like_behavior}")
    private String LikeTopic;
}
